package com.ajocer.springbootinit.config;

import io.github.resilience4j.ratelimiter.RateLimiter;
import io.github.resilience4j.ratelimiter.RateLimiterRegistry;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;

/**
 * 限流配置类
 */
@Configuration
public class RateLimiterConfig {

    /**
     * 创建RateLimiterRegistry
     */
    @Bean
    public RateLimiterRegistry rateLimiterRegistry() {
        return RateLimiterRegistry.ofDefaults();
    }

    /**
     * 全局默认限流器配置
     */
    @Bean
    public RateLimiter globalRateLimiter(RateLimiterRegistry registry) {
        io.github.resilience4j.ratelimiter.RateLimiterConfig config = io.github.resilience4j.ratelimiter.RateLimiterConfig.custom()
                .limitRefreshPeriod(Duration.ofSeconds(1))
                .limitForPeriod(100)  // 每秒允许100个请求
                .timeoutDuration(Duration.ofMillis(100))
                .build();
        
        return registry.rateLimiter("globalRateLimiter", config);
    }

    /**
     * AI接口限流器配置
     */
    @Bean
    public RateLimiter aiRateLimiter(RateLimiterRegistry registry) {
        io.github.resilience4j.ratelimiter.RateLimiterConfig config = io.github.resilience4j.ratelimiter.RateLimiterConfig.custom()
                .limitRefreshPeriod(Duration.ofSeconds(1))
                .limitForPeriod(10)  // 每秒允许10个请求
                .timeoutDuration(Duration.ofMillis(500))
                .build();
        
        return registry.rateLimiter("aiRateLimiter", config);
    }
} 